package com.aliware.tianchi;

import com.aliware.tianchi.policy.BaseConfig;
import com.aliware.tianchi.policy.LargeConfig;
import com.aliware.tianchi.policy.MediumConfig;
import com.aliware.tianchi.policy.SmallConfig;
import org.apache.commons.lang3.RandomStringUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author lorne
 * @date 2019/6/25
 * @description
 */
public class ThreadTest {

    public static void main(String[] args) {

        BaseConfig baseConfig = new LargeConfig();

        HashInterface hashInterface = new HashServiceImpl("",baseConfig.getConfigs());

        long t1 = System.currentTimeMillis();
        for (int i=1;i<=10;i++){
            test(hashInterface,1000,100);
        }

        long t2 = System.currentTimeMillis();
        System.out.println("all-time:"+(t2-t1));
        System.exit(0);
    }

    private static synchronized long test(HashInterface hashInterface,int count,int threads){
        long start = System.currentTimeMillis();
        AtomicLong time = new AtomicLong();
        ExecutorService executorService =  Executors.newFixedThreadPool(threads);
        for(int i=0;i<count;i++) {
            executorService.submit(() -> {
                long t1 = System.currentTimeMillis();
                String content = RandomStringUtils.randomAlphanumeric(16);
                hashInterface.hash(content);
                long t2 = System.currentTimeMillis();
                time.addAndGet(t2-t1);
            });
        }
        while (!executorService.isTerminated()){
            executorService.shutdown();
        }
        long avg = time.get()/count;
        long end = System.currentTimeMillis();
        System.out.println("threads:"+threads+",time:"+(end-start)+",avg:"+avg);
        return avg;
    }
}
